#include "server.h"

#define tries 5

bool access_server(const string &ip, const uint16_t &port, int &count)
{
    // 1.创建套接字(创建文件细节)
    int sockfd = socket(AF_INET, SOCK_STREAM, 0); // 创建套接字(域、套接字类型、协议)参数2基本可以固定tcp/udp
    if (sockfd < 0)
    {
        cerr << "创建套接字失败" << endl;
        exit(-1);
    }
    // 不需要调用bind函数绑定客户端的ip+port,在首次connect时会默认自动绑定
    // 客户端ip是由自己端决定，端口是临时端口

    // 2.与服务器建立连接(此时自动进行绑定)
    sockaddr_in sv;
    sv.sin_family = AF_INET;
    sv.sin_port = htons(port);
    inet_pton(AF_INET, ip.c_str(), &sv.sin_addr);

    if (connect(sockfd, (sockaddr *)&sv, sizeof(sv)) != 0)
    {
        cerr << "建立连接失败" << endl;
        close(sockfd);
        return false;
    }

    cout << "成功建立连接..." << endl;
    count = tries;

    while (1)
    {
        // 发数据
        string tmp;
        cout << "please input:";
        getline(cin, tmp);
        size_t n = write(sockfd, tmp.c_str(), tmp.size());
        if (n < 0)
        {
            return false;
        }

        // 收数据
        char buffer[1024];
        int ret = read(sockfd, buffer, sizeof(buffer) - 1);
        if (ret > 0)
            buffer[ret] = 0;
        else
            return false;
        cout << "client reading: " << buffer << endl;
    }
    return false;
}
int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        cerr << "erro input,please in:xxx ip port" << endl;
        exit(-1);
    }

    string ip = argv[1];
    uint16_t port = stoi(argv[2]);

    int count = tries;
    while (!access_server(ip, port, count))
    {
        cout << "重连中.... " << count << endl;
        sleep(1);
        count--;
        if (count == 0)
        {
            cout << "连接失败，已退出，请重新登陆...." << endl;
            break;
        }
    }

    return 0;
}